// 引入defineStore用于创建store
import { defineStore } from 'pinia'
import type { UserState } from './interface'
import { reqUserLogin } from "@/api/hospital";
import type { LoginData, UserLoginResponseData } from '@/api/hospital/type'
import { SET_TOKEN, GET_TOKEN,RMOVE_TOKEN } from '@/utils/user'
// 定义并暴露一个store
const useUserStore = defineStore('User', {
  // 动作
  actions: {
    async userLogin(LoginData: LoginData) {
      let res: UserLoginResponseData = await reqUserLogin(LoginData)
      if (res.code === 200 && res.data) {
        this.userInfo = res.data
        this.visiable = false
        SET_TOKEN(JSON.stringify(this.userInfo))
      }
    },
    logout() {
      this.userInfo = {
        name: '',
        token: ''
      }
      RMOVE_TOKEN()
    },
    queryState(){
      let timer = setInterval(()=>{
        if(GET_TOKEN()){
          this.visiable = false
          this.userInfo = JSON.parse(GET_TOKEN() as string);
          clearInterval(timer);
        }
      },1000)
    }

  },
  // 状态
  state: (): UserState => {
    return {
      visiable: false,
      userInfo: JSON.parse(GET_TOKEN() as string) || {}
    }
  },
  // 计算
  getters: {}
})
export default useUserStore